package me.yiyou.meihua.ui.page.dateqiuga

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.delay
import me.yiyou.meihua.R
import me.yiyou.meihua.data.BaGuaImage
import me.yiyou.meihua.data.xinghuo.ChatMessage
import me.yiyou.meihua.data.xinghuo.ChatUiState
import me.yiyou.meihua.element.CustomButton
import me.yiyou.meihua.utils.LogUtil
import me.yiyou.meihua.utils.getGuaNameByImgShang
import me.yiyou.meihua.utils.getGuaNameByImgXia

@Composable
fun DateQiGuaPage(viewModel: DateQiGuaViewModel = viewModel()) {

    val showDescribe by viewModel.showDescribe  // 是否显示占问事
    val inputContent by viewModel.inputContent  // 占问事内容

    var baGuaImage: BaGuaImage? = null
    var huGuaImage: BaGuaImage? = null
    var bianGuaImage: BaGuaImage? = null

    // 控制显示, 前置部分
    if (showDescribe) {
        Column(
            Modifier
                .fillMaxWidth()
                .padding(top = 80.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            val focusManager = LocalFocusManager.current
            Text(text = "请输入占问事")
            OutlinedTextField(
                value = inputContent,
                onValueChange = viewModel::onInputContentChange,
                label = { Text("占问事") },
                placeholder = { Text("请输入占问事") },
                keyboardOptions = KeyboardOptions(imeAction = ImeAction.Go),
                keyboardActions = KeyboardActions(
                    onSearch = {
                        viewModel.qiGua()
                        focusManager.clearFocus() // 收起键盘
                    }
                ),
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(10.dp)
            )
            CustomButton(
                text = "起卦",
                onClick = { viewModel.qiGua() },
                modifier = Modifier
                    .width(100.dp)
                    .padding(10.dp)
            )
        }
    }

    // 卦主体部分
    if (!showDescribe) {
        // 上下卦，动爻数据
        val shangGua by viewModel.shangGua
        val xiaGua by viewModel.xiaGua
        val dongYao by viewModel.dongYao

        Column(Modifier.fillMaxWidth()) {
            // 卦象部分
            Row(
                Modifier
                    .fillMaxWidth()
                    .padding(top = 60.dp, start = 10.dp, end = 10.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 本卦部分
                Column(Modifier.width(100.dp)) {
                    baGuaImage = viewModel.paintGua(shangGua, xiaGua)
                    if (dongYao == 6) GetSingleYao(
                        baGuaImage!!.six, true
                    ) else GetSingleYao(baGuaImage!!.six)

                    if (dongYao == 5) GetSingleYao(
                        baGuaImage!!.five, true
                    ) else GetSingleYao(baGuaImage!!.five)

                    if (dongYao == 4) GetSingleYao(
                        baGuaImage!!.four, true
                    ) else GetSingleYao(baGuaImage!!.four)

                    if (dongYao == 3) GetSingleYao(
                        baGuaImage!!.three, true
                    ) else GetSingleYao(
                        baGuaImage!!.three
                    )

                    if (dongYao == 2) GetSingleYao(
                        baGuaImage!!.two, true
                    ) else GetSingleYao(baGuaImage!!.two)

                    if (dongYao == 1) GetSingleYao(
                        baGuaImage!!.one, true
                    ) else GetSingleYao(baGuaImage!!.one)
                }
                // 互卦
                Column(Modifier.width(100.dp)) {
                    huGuaImage = getHuGuaImageMethod(baGuaImage!!)
                    GetSingleYao(huGuaImage!!.six)
                    GetSingleYao(huGuaImage!!.five)
                    GetSingleYao(huGuaImage!!.four)
                    GetSingleYao(huGuaImage!!.three)
                    GetSingleYao(huGuaImage!!.two)
                    GetSingleYao(huGuaImage!!.one)
                }
                // 变卦
                Column(Modifier.width(100.dp)) {
                    bianGuaImage = getBianGuaImageMethod(baGuaImage!!, dongYao)
                    GetSingleYao(bianGuaImage!!.six)
                    GetSingleYao(bianGuaImage!!.five)
                    GetSingleYao(bianGuaImage!!.four)
                    GetSingleYao(bianGuaImage!!.three)
                    GetSingleYao(bianGuaImage!!.two)
                    GetSingleYao(bianGuaImage!!.one)
                }
            }

            // 分析部分
            Column(
                Modifier
                    .fillMaxWidth()
                    .padding(top = 20.dp, start = 10.dp, end = 10.dp),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                Text(
                    text = "主卦: ${getGuaNameByImgShang(baGuaImage!!)} + ${
                        getGuaNameByImgXia(
                            baGuaImage!!
                        )
                    } + ${dongYao}爻动 ", fontSize = 18.sp
                )
                Text(
                    text = "互卦: ${getGuaNameByImgShang(huGuaImage!!)} + ${
                        getGuaNameByImgXia(
                            huGuaImage!!
                        )
                    } ", fontSize = 18.sp
                )
                Text(
                    text = "变卦: ${getGuaNameByImgShang(bianGuaImage!!)} + ${
                        getGuaNameByImgXia(
                            bianGuaImage!!
                        )
                    } ", fontSize = 18.sp
                )
            }

            // 时间部分
            Column(
                Modifier
                    .fillMaxWidth()
                    .padding(top = 20.dp, start = 10.dp, end = 10.dp)
            ) {
                Text(text = "起卦时间: ${viewModel.time}", fontSize = 16.sp, color = Color.Gray)
                Text(
                    text = "占问事: ${viewModel.inputContent.value}",
                    fontSize = 16.sp,
                    color = Color.Gray
                )
            }

            if (viewModel.aiButton.value == true) {
                Column(
                    Modifier.fillMaxWidth(),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    CustomButton(
                        text = "AI解卦",
                        onClick = {
                            getAiAnswer(
                                baGuaImage!!,
                                huGuaImage!!,
                                bianGuaImage!!,
                                dongYao,
                                viewModel
                            )
                        },
                        modifier = Modifier
                            .width(120.dp)
                            .padding(10.dp)
                            .fillMaxWidth()
                    )
                }
            }

            // AI 解答
            val chatResponse by viewModel.chatResponse
                .collectAsStateWithLifecycle(initialValue = null)

            // 从状态中动态获取内容
            val content = chatResponse?.choices?.firstOrNull()?.message?.content
                ?: "分析结果加载中..."
            if (viewModel.aiButton.value == false) {
                // 普通回复
//                LazyColumn(
//                    modifier = Modifier
//                        .fillMaxWidth()
//                        .padding(10.dp)
//                        .height(260.dp)
//                ) {
//                    item {
//                        Text(
//                            text = content,
//                            fontSize = 12.sp,
//                            color = Color.Gray
//                        )
//                    }
//                }

                // 流式回复
                val messages by viewModel.messages.collectAsState()
                val uiState by viewModel.uiState.collectAsState()
                val scrollState = rememberLazyListState()


                // 自动滚动到底部
//                LaunchedEffect(messages) {
//                    if (messages.isNotEmpty()) {
//                        scrollState.scrollToItem (messages.size - 1, scrollOffset = 0)
//                    }
//                }

                // 聊天消息列表
                LazyColumn(
                    state = scrollState,
                    modifier = Modifier
                        .weight(1f)
                        .padding(8.dp)
                ) {
                    items(
                        items = messages,
                        key = { it.id }  // 现在使用消息ID作为键
                    ) { message ->
                        MessageBubble(
                            message = message,
                            isUser = message.isUser
                        )
                    }
                }

                // 加载状态
                when (uiState) {
                    is ChatUiState.Loading -> {
                        LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
                    }

                    is ChatUiState.Error -> {
                        val error = (uiState as ChatUiState.Error).message
                        Text(
                            text = "错误: $error",
                            color = Color.Red,
                            modifier = Modifier.padding(8.dp)
                        )
                    }

                    else -> {}
                }
            }
        }
    }
}

@Composable
fun MessageBubble(message: ChatMessage, isUser: Boolean) {
    val bgColor = if (isUser) Color(0xFFDCF8C6) else Color(0xFFFFFFFF)
    val alignment = if (isUser) Alignment.End else Alignment.Start

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp),
        horizontalAlignment = alignment
    ) {
        Box(
            modifier = Modifier
                .clip(RoundedCornerShape(8.dp))
                .background(bgColor)
                .padding(horizontal = 12.dp, vertical = 8.dp)
        ) {
            // 添加打字效果动画
            AnimatedTextContent(message.text, isUser)
        }
    }
}

@Composable
fun AnimatedTextContent(text: String, isUser: Boolean) {
    // 只对非用户消息且包含占位符█的文本应用动画
    if (!isUser && text.contains("█")) {
        var animatedText by remember { mutableStateOf("") }
        var cursorVisible by remember { mutableStateOf(true) }

        // 打字效果动画
        LaunchedEffect(text) {
            // 移除文本中的█字符，然后逐步显示
            val cleanText = text.replace("█", "")
            for (i in 1..cleanText.length) {
                animatedText = cleanText.substring(0, i) + if (cursorVisible) "█" else ""
                delay(30) // 控制打字速度
            }
            // 移除光标
            animatedText = cleanText
        }

        // 光标闪烁效果
        LaunchedEffect(cursorVisible) {
            while (text.contains("█")) {
                delay(500)
                cursorVisible = !cursorVisible
            }
        }

        Text(
            text = animatedText,
            fontSize = 16.sp
        )
    } else {
        // 用户消息或已完成的消息直接显示
        Text(
            text = text,
            fontSize = 16.sp
        )
    }
}

/**
 * 获取AI回答(AI解卦)
 */
fun getAiAnswer(
    baGuaImage: BaGuaImage,
    huGuaImage: BaGuaImage,
    bianGuaImage: BaGuaImage,
    dongYao: Int,
    viewModel: DateQiGuaViewModel
) {
    val tempShang = getGuaNameByImgShang(baGuaImage)   // 获取主卦的上下挂
    val tempXia = getGuaNameByImgXia(baGuaImage)

    // 因为这里用的是讯飞星火的api,有点傻逼,(傻逼为啥还用??谁让他免费额度比较大呢),所以最好给他指定出互卦和变卦来
    val tempHShang = getGuaNameByImgShang(huGuaImage)
    val tempHXia = getGuaNameByImgXia(huGuaImage)

    val tempBShang = getGuaNameByImgShang(bianGuaImage)
    val tempBXia = getGuaNameByImgXia(bianGuaImage)

    LogUtil.e("主卦上卦${tempShang},下卦${tempXia},互卦上卦${tempHShang},互卦下卦${tempHXia},变卦上卦${tempBShang},变卦下卦${tempBXia}, 动爻${dongYao}爻")
    // 调用ai
//    viewModel.getChatResponse(
//        "x1", "user_yiyou_236",
//        "分析梅花易数卦象:主卦上卦${tempShang},下卦${tempXia},互卦上卦${tempHShang},互卦下卦${tempHXia},变卦上卦${tempBShang},变卦下卦${tempBXia}, " +
//                "动爻${dongYao}爻,占问事为${viewModel.inputContent.value}"
//    ) { result ->
//        // 回调拿结果,其实可以不用,直接那viewmodel中的数据,方便看数据
//        if (result.isSuccess) {
//            Log.d("getChatResponse", "success: $result")
//        } else {
//            Log.d("getChatResponse", "error: ${result.exceptionOrNull()}")
//        }
//    }

    viewModel.sendMessage(
        "分析梅花易数卦象:主卦上卦${tempShang},下卦${tempXia},互卦上卦${tempHShang},互卦下卦${tempHXia},变卦上卦${tempBShang},变卦下卦${tempBXia}, " +
                "动爻${dongYao}爻,占问事为${viewModel.inputContent.value}"
    )
}


/**
 * 画变卦,根据本卦计算互卦
 */
fun getBianGuaImageMethod(baGuaImage: BaGuaImage, dong: Int): BaGuaImage {
    val final = BaGuaImage(
        six = baGuaImage.six,
        five = baGuaImage.five,
        four = baGuaImage.four,
        three = baGuaImage.three,
        two = baGuaImage.two,
        one = baGuaImage.one
    )
    if (dong == 6) {
        final.six = !final.six
    }
    if (dong == 5) {
        final.five = !final.five
    }
    if (dong == 4) {
        final.four = !final.four
    }
    if (dong == 3) {
        final.three = !final.three
    }
    if (dong == 2) {
        final.two = !final.two
    }
    if (dong == 1) {
        final.one = !final.one
    }
    return final
}

/**
 * 画互卦,根据本卦计算互卦
 */
fun getHuGuaImageMethod(baGuaImage: BaGuaImage): BaGuaImage {
    return BaGuaImage(
        six = baGuaImage.five,
        five = baGuaImage.four,
        four = baGuaImage.three,
        three = baGuaImage.four,
        two = baGuaImage.three,
        one = baGuaImage.two
    )
}

/**
 * 画卦,单爻
 */
@Composable
fun GetSingleYao(bol: Boolean, dong: Boolean? = false) {
    Row(
        Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.Center,
        verticalAlignment = Alignment.CenterVertically
    ) {
        if (dong!!) {
            Text(text = "○", modifier = Modifier.width(10.dp))
        } else {
            Text(text = "", modifier = Modifier.width(10.dp)) // 占位符
        }
        Image(
            painter = painterResource(id = if (bol) R.mipmap.yangyao else R.mipmap.yinyao),
            contentDescription = null,
            modifier = Modifier.width(90.dp)
        )
    }
}